iT邦幫忙

2024 iThome 鐵人賽

DAY 13
0

這篇介紹如何在 kintone 中插入 Google 地圖並顯示在單筆紀錄中,其實就只是將 iframe 嵌入到紀錄而已,不過我們會需要座標才能顯示地圖,所以開始之前要先建立出兩個單行文字方塊的欄位紀錄座標,以及空白欄位顯示地圖。

在下篇文章我們才會將地址轉為座標,這篇就純粹用座標顯示出地圖。

開發環境建置

首先建立專案:

npm create krsb

我使用 Vue + TS 開發,接著在 kintone 中設定好欄位,分別是以下:

欄位類型 欄位 ID
單行文字方塊 lat
單行文字方塊 lng
空白欄位 map

完成後就接著開發啦!

建立型別

建立 types 資料夾再新增 index.ts

type EventWrapper<T> = {
  appId: number;
  recordId: number;
  type: string;
  record: T;
};

type RecordType = {
  $id: kintone.fieldTypes.Id;
  lat: kintone.fieldTypes.SingleLineText;
  lng: kintone.fieldTypes.SingleLineText;
};

export type DetailEvent = EventWrapper<RecordType>

composable

開一個名為 composables 的資料夾並建立 useIframeMap.ts,內容是:

import { ref, onBeforeMount, inject } from 'vue'
import type { DetailEvent } from '../types'

type Coordinate = {
  lng: string
  lat: string
}

export const useIframeMap = () => {
  const edtailEvent = inject<DetailEvent>('event')!
  const iframeSrc = ref('')

  const getIframeSrc = (coordinate: Coordinate) => {
    const { lng, lat } = coordinate
    return `https://maps.google.com/maps?q=${lat},${lng}&z=16&output=embed`
  }

  const getCoordinate = (event: DetailEvent) => {
    const lat = event.record.lat.value
    const lng = event.record.lng.value
    return { lat, lng }
  }

  onBeforeMount(() => {
    const coordinate = getCoordinate(edtailEvent)
    iframeSrc.value = getIframeSrc(coordinate)
  })

  return { iframeSrc }
}

這個主要用來取得顯示在畫面上的地圖 src。

component

建立 components 資料夾並建立 GoogleMap.vue

<script setup lang="ts">
import { useIframeMap } from '../composables/useIframeMap'

const { iframeSrc } = useIframeMap()
</script>

<template>
  <iframe :src="iframeSrc" frameborder="0" style="width: 500px; height: 500px;"></iframe>
</template>

主檔案 index.ts

index.ts 中,會希望將 event 傳遞至子元件:

import { createApp } from 'vue'
import GoogleMap from './components/GoogleMap.vue'

kintone.events.on('app.record.detail.show', (event) => {
  const el = kintone.app.record.getSpaceElement('map')
  if (!el) return
  createApp(GoogleMap)
    .provide('event', event)
    .mount(el)
})

完成之後,當我們嘗試在欄位中新增座標,就可以發現地圖顯示在紀錄上面了:


上一篇
Day 12 | kintone 隱藏欄位內容,直到滑鼠經過
系列文
我阿嬤都會的 kintone 客製化開發13
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言